<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

</head>

<body>

    <div id="app">
        <p>
            Ask a yes/no question:
            <input v-model="question" :disabled="loading" />
        </p>
        <p>{{ answer }}</p>
    </div>
</body>

<script>
    const { createApp } = Vue

    const vm = createApp({
        data() {
            return {
                question: '',
                answer: 'Questions usually contain a question mark. ;-)',
                loading: false,
            }
        },
        watch: {
            // 每当 question 改变时，这个函数就会执行
            question(newQuestion, oldQuestion) {
                console.log(newQuestion, '111111');
                if (newQuestion.includes('?')) {
                    this.getAnswer()
                }
            }
        },
        methods: {
            async getAnswer() {
                this.loading = true
                this.answer = 'Thinking...'
                try {
                    const res = await fetch('https://yesno.wtf/api')
                    this.answer = (await res.json()).answer
                } catch (error) {
                    this.answer = 'Error! Could not reach the API. ' + error
                } finally {
                    this.loading = false
                }
            }
        }
    }).mount('#app')


</script>

</html>